/**
 * Created by henian.xu on 2018/6/25.
 * 超链接混合器
 */

const urlReg = new RegExp(/[a-zA-z]+:\/\/[^\s]*/);

export default {
    props: {
        to: {
            type: [String, Object],
            default: '',
            required: true,
        },
        tag: {
            type: String,
            default: '',
        },
        exact: Boolean,
        append: Boolean,
        replace: Boolean,
        activeClass: String,
        exactActiveClass: String,
        event: {
            type: [String, Array],
            default: 'click',
        },
        disabled: Boolean,
        /**
         * 因为 nuxt-link 跳转时会使用客服端渲染，
         * 些选项为 true 时转为 a 标签或 window.location.href 跳转，会使用服务渲染。
         */
        ssr: Boolean,
    },
    computed: {
        isUrl() {
            return urlReg.test(this.to);
        },
        linkerProps() {
            const { to, tag, exact, append, replace, activeClass, exactActiveClass, event, disabled } = this;
            if (!to || disabled) {
                return {};
            } else if (this.isUrl || this.ssr) {
                return {
                    is: tag || 'a',
                    href: tag ? undefined : to,
                };
            } else {
                return {
                    // is: 'router-link',
                    to,
                    tag: tag || 'a',
                    exact,
                    append,
                    replace,
                    activeClass,
                    exactActiveClass,
                    event,
                };
            }
        },
        listeners() {
            const { $listeners, isUrl, ssr, tag } = this;
            const listener = { ...$listeners };
            if ((isUrl || ssr) && tag) {
                listener.click = this.onClick;
            }
            return listener;
        },
        classes() {
            if (!this.ssr) return [];
            const { $router, $route, to } = this;
            const { linkActiveClass, linkExactActiveClass } = $router.options;
            if (to === $route.path) return [linkExactActiveClass];
            if (!$route.path.indexOf(to)) return [linkActiveClass];
            return [];
        },
    },
    methods: {
        onClick() {
            window.location.href = this.to;
        },
    },
};
